package org.apache.servicecomb.fence.resource;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.sql.UpdateResult;
import org.apache.servicecomb.fence.api.resource.VertxResponseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

@Service
public class VertxResponseLogicService {
    private static final Logger LOGGER = LoggerFactory.getLogger(VertxResponseLogicService.class);


    @Autowired
    private VertxResponseMapper rocketMqMsgMapper;

    public VertxResponseInfo getById(Long id) {

        if (id == null) {
            throw  new RuntimeException("无有效id");
        }
        return rocketMqMsgMapper.getById(id);
    }



    public VertxResponseInfo getAsnyById(Long id) {

        VertxResponseInfo info = new VertxResponseInfo();
        if (id == null) {
            throw  new RuntimeException("无有效id");
        }
        Vertx vertx = Vertx.vertx();
        VertxJdbcConfig jdbcConfig = VertxJdbcConfig.create(vertx);
        jdbcConfig.getJdbcClient().getConnection(res -> {
            SQLConnection connection = res.result();
            JsonArray params = new JsonArray().add(id);
            if (res.succeeded()){
                connection.queryWithParams("select * from vertx_response_info where id = ?",params,e -> {
                    if (e.failed()){
                        System.out.println(e);
                        return;
                    }
                    ResultSet result = e.result();
                    LOGGER.info(result.getRows().toString());
                    System.out.println(result.getRows());
                });
            }else {

            }
        });

        return info;
    }

    public int insert(String RESPONSEINFO){
        AtomicInteger id = new AtomicInteger();
        Vertx vertx = Vertx.vertx();
        VertxJdbcConfig jdbcConfig = VertxJdbcConfig.create(vertx);
        jdbcConfig.getJdbcClient().getConnection(res->{
            SQLConnection connection = res.result();
            String sql = "insert into vertx_response_info(RESPONSEINFO) values(?)";
            connection.updateWithParams(sql,
                    new JsonArray().add(RESPONSEINFO),
                    (ar) -> {
                        if (ar.failed()) {
                            return;
                        }
                        UpdateResult result = ar.result();
                        // Build a new whisky instance with the generated id.
                        id.set(result.getKeys().getInteger(0));
                    });
        });
        return id.get();

    }



}
